package com.itheima.day01;

import java.util.concurrent.locks.ReentrantLock;

public class LockTest implements  Runnable {
    private int ticket=100;
    private Object obj=new Object();
    private ReentrantLock lock=new ReentrantLock();

    @Override
    public void run() {
        //lockMethod();
        while (true){
            synchronized (obj){
                if (ticket==0){
                    break;
                }else{
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    ticket--;
                    System.out.println(Thread.currentThread().getName()+"在买票，还剩"+ticket+"张票");
                }
            }
        }
    }

    private void lockMethod() {
        while (true) {
            try {
                lock.lock();
                if (ticket<=0){
                    break;
                }else{
                        Thread.sleep(100);
                    }
                    ticket--;
                    System.out.println(Thread.currentThread().getName()+"在买票，还剩"+ticket+"张");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }
}
